-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2429. Minimize XOR.cpp
More file actions
51 lines (41 loc) · 1.14 KB
/
Copy path2429. Minimize XOR.cpp
File metadata and controls
51 lines (41 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
Problem Name: Leetcode 2429. Minimize XOR
https://leetcode.com/problems/minimize-xor/description/
Company :
*/
/*
Time Complexity : O(31) = O(1)
Space Complexity : O(1)
*/
class Solution {
public:
bool isSet(int &x, int bit) {
return x & (1 << bit);
}
bool setBit(int &x, int bit) {
return x |= (1 << bit);
}
bool unsetBit(int &x, int bit) {
return x &= ~(1 << bit);
}
bool isUnset(int x, int bit) {
return (x & (1 << bit)) == 0;
}
int minimizeXor(int num1, int num2) {
int x = 0;
int requiredSetBitCount = __builtin_popcount(num2);
for(int bit = 31; bit >= 0 && requiredSetBitCount > 0; bit--) {
if(isSet(num1, bit)) {
setBit(x, bit); //Or you can write x |= (1 << bit);
requiredSetBitCount--;
}
}
for(int bit = 0; bit < 32 && requiredSetBitCount > 0; bit++) {
if(isUnset(num1, bit)) {
setBit(x, bit); //Or you can write x |= (1 << bit);
requiredSetBitCount--;
}
}
return x;
}
};